#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File  :pantum_alert.py
# Time  :2025/5/19 10:18
# Email :fortunatedong@163.com
# Author:by Adonli

"""
Pantum工单监控系统
- 自动检测工单状态
- 请求失败时自动重新登录获取新cookie
- 定时执行任务
"""

import datetime
import time
from datetime import datetime
import json
import os
import re
import subprocess
import sys

import requests
import schedule
import toml

from config import ROOT_DIR
from utils.monitoring_early_warning.dingtalk.pantum_dingtalk import MessagePush
# 文件路径
pantum_cookie_json = os.path.join(ROOT_DIR, 'utils/monitoring_early_warning/auth', 'pantum_cookie.json')
pantum_login_script = os.path.join(ROOT_DIR, 'utils/monitoring_early_warning', 'pantum_login.py')


class PantumAlert:
    def __init__(self):
        self.url = 'https://css.pantum.com/admin/common/index.jhtml'
        self.max_retries = 3  # 最大重试次数
        self.retry_delay = 5  # 重试间隔(秒)

    def load_cookies(self):
        """加载cookie"""
        try:
            with open(pantum_cookie_json, 'r') as f:
                cookie_json = json.load(f)
            return {cookie['name']: cookie['value'] for cookie in cookie_json}
        except (FileNotFoundError, json.JSONDecodeError, KeyError) as e:
            print(f"加载cookie失败: {str(e)}")
            return None

    def refresh_cookies(self):
        """运行登录脚本刷新cookie"""
        print("尝试刷新cookie...")
        try:
            # 使用subprocess运行登录脚本
            result = subprocess.run(
                [sys.executable, pantum_login_script],
                check=True,
                capture_output=True,
                text=True,
                encoding='utf-8',  # 显式指定编码
                errors='ignore'  # 忽略解码错误
            )
            print("登录脚本输出:", result.stdout)
            if result.returncode != 0:
                print("登录脚本执行失败:", result.stderr)
                return False
            return True
        except subprocess.CalledProcessError as e:
            print(f"执行登录脚本失败: {str(e)}")
            return False

    def make_request(self, retry_count=0):
        """带重试机制的请求函数"""
        cookie_dict = self.load_cookies()
        if not cookie_dict:
            print("无法加载cookie，尝试刷新...")
            if not self.refresh_cookies():
                return None
            cookie_dict = self.load_cookies()
            if not cookie_dict:
                return None

        try:
            headers = {
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
                'Accept-Encoding': 'gzip, deflate, br, zstd',
                'Cookie': f'password={cookie_dict.get("password", "")}; token={cookie_dict.get("token", "")}; JSESSIONID={cookie_dict.get("JSESSIONID", "")}',
                'Host': 'css.pantum.com',
                'Referer': 'https://css.pantum.com/admin/common/main.jhtml',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36',
            }

            response = requests.get(self.url, headers=headers, timeout=30)
            match_login = re.search("请输入您的用户名", response.text)
            if match_login:
                raise requests.RequestException("登录页面出现，请求被终止")  # 手动抛出异常

            return response.text

        except (requests.RequestException, requests.Timeout) as e:
            print(f"请求失败: {str(e)}")
            if retry_count < self.max_retries:
                print(f"{self.retry_delay}秒后重试({retry_count + 1}/{self.max_retries})...")
                time.sleep(self.retry_delay)

                # 最后一次重试前尝试刷新cookie
                if retry_count == self.max_retries - 2:
                    if self.refresh_cookies():
                        return self.make_request(retry_count + 1)

                return self.make_request(retry_count + 1)
            else:
                print("达到最大重试次数，请求失败")
                return None

    def alert_message(self):
        """获取工单信息"""
        html_content = self.make_request()
        # print(html_content)
        if not html_content:
            print("无法获取网页内容")
            return None

        try:
            # 使用正则表达式提取工单信息
            # reg = re.compile(
            #     r'<div class="gongdan_list">提醒工单1</div>.*?<ul>.*?<li>(.*?)<span class = "num">(.*?)</span></li>.*?<li>(.*?)<a href=.*?<span class = "num">(.*?)</span></a></li>.*?<li>(.*?)<a href=.*?<span class = "num">(.*?)</span></a></li>.*?<li>(.*?)<a href=.*?onclick=.*?<span class = "num">(.*?)</span></a></li>',
            #     re.S
            # )
            reg = re.compile(
                r'<div class="gongdan_list">提醒工单1</div>.*?<span class = "num">(.*?)</span></li>.*?<span class = "num">(.*?)</span>.*?<span class = "num">(.*?)</span></a>.*?<span class = "num">(.*?)</span></a></li>',
                re.S
            )
            result = re.findall(reg, html_content)

            if not result:
                print("未找到工单信息")
                return None
            total_orders = result[0][0]
            waiting_appointment = result[0][1]
            waiting_completion = result[0][2]
            waiting_confirmation = result[0][3]
            pantum_order1 = {'total_orders':total_orders,
                             'waiting_appointment':waiting_appointment,
                             'waiting_completion':waiting_completion,
                             'waiting_confirmation':waiting_confirmation}
            if int(waiting_completion) > 0:
                configs_toml = os.path.join(ROOT_DIR, 'utils/monitoring_early_warning', 'configs.toml')
                with open(configs_toml, "r", encoding="utf-8") as f:
                    cfg = toml.load(f)
                last_ids = cfg['BENTUMORDER']['Order400']
                print(f"上一次监控待完工的单号:{last_ids}")
                pramas = {
                    "inOrOut":"",
                    "stat":3,
                    "flag":"",
                    "serviceType":"",
                    "serviceTypeId":"",
                    "dispatchStat":"",
                    "orderTypeId":13,
                    "swtCreateDate":"",
                    "orderNo":"",
                    "engineerName":"",
                    "takeDateStart":"",
                    "takeDateEnd":"",
                    "userName":"",
                    "userMobile":"",
                    "inAndOutCode":"",
                    "completeDateStart":"",
                    "completeDateEnd":"",
                    "tipName":"",
                    "areaId":"",
                    "areaId_select":"",
                    "userAddress":"",
                    "completeComfirmDateStart":"",
                    "completeComfirmDateEnd":"",
                    "pageSize":20,
                    "searchProperty":"",
                    "orderProperty":"",
                    "takeDate":"",
                    "orderDirection":"desc",
                }
                cookie_dict2 = self.load_cookies()
                headers2 = {
                    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
                    'Accept-Encoding': 'gzip, deflate, br, zstd',
                    'Cookie': f'password={cookie_dict2.get("password", "")}; token={cookie_dict2.get("token", "")}; JSESSIONID={cookie_dict2.get("JSESSIONID", "")}',
                    'Host': 'css.pantum.com',
                    'Referer': 'https://css.pantum.com/admin/common/main.jhtml',
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36',
                }
                response2 = requests.get("https://css.pantum.com/admin/mysite/list.jhtml",params=pramas,headers=headers2)
                # print(response2.text)
                reg2 = re.compile('<td class="operation">.*?onclick="bb\\((.*?)\\);">(.*?)</a>',re.S)
                ids = re.findall(reg2, response2.text)
                ids_result = {k: v for k, v in ids}
                ids_result_list = [value for key, value in ids_result.items()]
                print(f"本次监控待完工的单号:{ids_result_list}")
                if ids_result:
                    new_ids = [value for key,value in ids_result.items() if value not in last_ids]
                    print(f"本次监控新增待完工新单号:{new_ids}")
                    if new_ids:
                        MessagePush(new_ids).pantum_alert_message()
                        with open(configs_toml, "r", encoding="utf-8") as f:
                            cfg = toml.load(f)
                        cfg['BENTUMORDER']['Order400'] = ids_result_list
                        with open(configs_toml, 'w', encoding="utf-8") as f:
                            toml.dump(cfg, f)
                        print(f"本次已更新Order400单号记录:{ids_result_list}")
                    else:
                        print(f"本次监控无新增待完工新单号")
                return ids_result
            else:
                print("未找到待完工工单，待完工工单总数为0")

        except Exception as e:
            print(f"解析工单信息失败: {str(e)}")
            return None


def run_pantum_alert():
    """检查当前时间是否在8:00-20:00之间，如果是则执行任务"""
    now = datetime.now().time()
    starttime = datetime.strptime('08:00', '%H:%M').time()
    endtime = datetime.strptime('20:00', '%H:%M').time()

    if starttime <= now <= endtime:
        print(f"{datetime.now().strftime('%H:%M')} 正在执行Pantum工单检查...")
        alert = PantumAlert()
        return alert.alert_message()
    else:
        print(f"{datetime.now().strftime('%H:%M')} 当前时间不在工作时段(8:00-20:00)")
        return None


if __name__ == '__main__':
    print("启动Pantum工单监控系统...")

    # 立即运行一次（如果当前时间在8:00-20:00之间）
    run_pantum_alert()

    # 设置定时任务（每30分钟运行一次）
    schedule.every(10).minutes.do(run_pantum_alert)

    # 保持主程序运行
    while True:
        schedule.run_pending()
        time.sleep(60)  # 每分钟检查一次，减少CPU占用